package com.paishen.peiniwan.module.set;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.ActivityCollector;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.module.login.AmazingLRActivity;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

public class SetEditPasswordActivity extends BaseActivity {

    private Button btnConfirm;

    private ImageView imgPwdOld, imgPwdNew, imgPwd2;
    private EditText edPwdOld, edPwdNew, edPwd2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_edit_password);

        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        layTitle.pushContent(makeBackView(), getString(R.string.set_edit_password), null, false);

        imgPwdOld = (ImageView) findViewById(R.id.img_pwd_old);
        imgPwdNew = (ImageView) findViewById(R.id.img_pwd_new);
        imgPwd2 = (ImageView) findViewById(R.id.img_pwd_2);
        edPwdOld = (EditText) findViewById(R.id.ed_pwd_old);
        edPwdNew = (EditText) findViewById(R.id.ed_pwd_new);
        edPwd2 = (EditText) findViewById(R.id.ed_pwd_2);

        edPwdOld.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean emptyText = TextUtils.isEmpty(edPwdOld.getText());
                imgPwdOld.setImageResource(!emptyText ? R.mipmap.edit_lock_focus : R.mipmap.edit_lock_normal);
            }
        });

        edPwdNew.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean emptyText = TextUtils.isEmpty(edPwdNew.getText());
                imgPwdNew.setImageResource(!emptyText ? R.mipmap.edit_password_focus : R.mipmap.edit_password_normal);
            }
        });

        edPwd2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean emptyText = TextUtils.isEmpty(edPwd2.getText());
                imgPwd2.setImageResource(!emptyText ? R.mipmap.edit_password_focus : R.mipmap.edit_password_normal);
            }
        });

        btnConfirm = (Button) findViewById(R.id.btn_confirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hideSoftInputFromWindowAlways(SetEditPasswordActivity.this);
                if (checkEditPassword(true)) {
                    String old_pwd = edPwdOld.getText().toString();
                    String new_pwd = edPwdNew.getText().toString();
                    requestChangePassword(old_pwd, new_pwd);
                }
            }
        });

        findViewById(R.id.lay_container).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hideSoftInputFromWindowAlways(SetEditPasswordActivity.this);
            }
        });
    }

    private void requestChangePassword(String old_pwd, final String new_pwd) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.User.changePassword(TAG, old_pwd, new_pwd, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    com.paishen.peiniwan.database.User user = App.i().getUser();
                    user.setPassword(new_pwd);
                    user.setApp_auto_login(false);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, user));

                    MobclickAgent.onProfileSignOff();
                    JPushInterface.stopPush(getApplicationContext());

                    EMClient.getInstance().logout(true, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                        }

                        @Override
                        public void onError(int code, String message) {
                        }
                    });

                    Intent intent = new Intent(SetEditPasswordActivity.this, AmazingLRActivity.class);
                    intent.putExtra(AmazingLRActivity.EXTRA_MODE_LOGIN, true);
                    startActivity(intent);
                    ActivityCollector.finishAllExcept(AmazingLRActivity.class);

                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private boolean checkEditPassword(boolean remind) {
        int minPwdLength = 6;

        boolean result = edPwdOld.getText().length() >= minPwdLength
                && edPwdNew.getText().length() >= minPwdLength
                && edPwd2.getText().length() >= minPwdLength;

        if (result && !TextUtils.equals(edPwdNew.getText(), edPwd2.getText())) {
            result = false;
            if (remind) BaseUtil.showToast(R.string.set_input_password_fail_diff);
        } else if (result && TextUtils.equals(edPwdNew.getText(), edPwdOld.getText())) {
            result = false;
            if (remind) BaseUtil.showToast(R.string.set_password_fail_no_changed);
        } else if (!result) {
            if (remind) BaseUtil.showToast(R.string.register_input_set_pwd);
        }

        return result;
    }
}
